//
//  NFKBaseWebViewController.swift
//  NFKTicket
//
//  Created by 大洋 on 2022/9/25.
//

import UIKit
import WebKit

let ScriptMessageHandlerForName = "__NFKNative__"

class NFKBaseWebViewController: UIViewController, UIScrollViewDelegate {
    var requestFullURL: String = ""
    
    private lazy var configuration: WKWebViewConfiguration = {
        let config = WKWebViewConfiguration()
        config.allowsInlineMediaPlayback = true
        config.preferences = WKPreferences()
        config.preferences.javaScriptCanOpenWindowsAutomatically = true
        config.allowsInlineMediaPlayback = true
        return config
    }()

    private lazy var userContentController: WKUserContentController = {
       let userContent = WKUserContentController()
        return userContent
    }()
    
    lazy var baseWebView: NFKWebView = {
        let view = NFKWebView(frame: .zero, configuration: configuration)
        view.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        view.isOpaque = false
        view.backgroundColor = .clear
        view.allowsLinkPreview = false
        view.translatesAutoresizingMaskIntoConstraints = false
        view.sizeToFit()
        return view
    }()
    
    private lazy var progressView: UIProgressView = {
        let progress = UIProgressView(progressViewStyle: .default)
        progress.tintColor = UIColor.blue
        progress.trackTintColor = .clear
        progress.isHidden = true
        return progress
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        view.backgroundColor = .white
        initWebView()
    }
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//        userContentController.add(self, name: ScriptMessageHandlerForName)
//    }
//    override func viewWillDisappear(_ animated: Bool) {
//        super.viewWillDisappear(animated)
//        userContentController.removeScriptMessageHandler(forName: ScriptMessageHandlerForName)
//    }
 
    deinit {
        baseWebView.removeObserver(self, forKeyPath: "estimatedProgress")
        baseWebView.stopLoading()
        baseWebView.uiDelegate = nil
        baseWebView.navigationDelegate = nil
    }
}

extension NFKBaseWebViewController {
    func initWebView() {

        view.addSubview(progressView)
        progressView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(UIDevice.xp_navigationFullHeight())
        }
        view.addSubview(baseWebView)
        baseWebView.snp.makeConstraints { make in
            make.bottom.leading.trailing.equalToSuperview()
            make.top.equalTo(progressView.snp.bottom)
        }
    }
}

extension NFKBaseWebViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
    }
}

extension NFKBaseWebViewController {
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let view = object as? NFKWebView, view == baseWebView {
            if let url = baseWebView.url?.absoluteString, url.count > 0 || baseWebView.estimatedProgress < 1.0 {
                progressView.isHidden = false
            }
            let animated = baseWebView.estimatedProgress > Double(progressView.progress)
            progressView.setProgress(Float(baseWebView.estimatedProgress), animated: animated)
            if baseWebView.estimatedProgress >= 1.0 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                    UIView.animate(withDuration: 0.25, delay: 0.25, options: .curveEaseOut) {
                        self.progressView.isHidden = true
                    } completion: { finish in
                        self.progressView.setProgress(0.0, animated: false)
                    }
                }
            }
        }
    }
}

